package com.czl.module_storehouse.activity.remand.selectedgoods;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.Button;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czl.base.data.bean.tengyun.RecordRemandBean;
import com.czl.base.data.bean.tengyun.SortBean;
import com.czl.base.util.SpHelper;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_service.system.Constants;
import com.czl.module_storehouse.R;
import com.czl.module_storehouse.activity.base.BaseOperationActivity;
import com.czl.module_storehouse.activity.intostore.saveloc.SaveLocActivity;
import com.czl.module_storehouse.activity.intostore.selectgoods.SelectGoodsActivity;
import com.czl.module_storehouse.activity.remand.selected.RemandSelectedOrderActivity;
import com.czl.module_storehouse.adapter.RemandSelectedGoodsAdapter;
import com.czl.module_storehouse.bean.RemandReturnBean;
import com.czl.module_storehouse.databinding.ActivityRemandSelectedGoodsBinding;
import com.czl.module_storehouse.event.OperationEvent;
import com.czl.module_storehouse.event.RecordRemandBeanEvent;
import com.czl.module_storehouse.event.RemandSelectOrderEvent;
import com.czl.module_storehouse.event.RemandSelectedGoodsEvent;
import com.czl.module_storehouse.event.SaveLocationEvent;
import com.czl.module_storehouse.listener.OnItemChangeListener;
import com.czl.module_storehouse.mvp.presenter.RemandHomePresenter;
import com.czl.module_storehouse.mvp.view.RemandHomeView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择物品归还
 *
 * @author xubin
 */
public class RemandSelectedGoodsActivity extends BaseOperationActivity<ActivityRemandSelectedGoodsBinding> implements RemandHomeView {

    private final RemandReturnBean mRemandReturnBean = new RemandReturnBean();
    private SortBean mSortBean;
    @InjectPresenter
    RemandHomePresenter mRemandHomePresenter;
    private RemandSelectedGoodsAdapter mAdapter;
    private final String locationName = SpHelper.INSTANCE.decodeString(Constants.SpKey.STOREHOUSE_LOCATION_NAME);
    private final int locationId = SpHelper.INSTANCE.decodeInt(Constants.SpKey.STOREHOUSE_LOCATION_ID);

    @Override
    protected ActivityRemandSelectedGoodsBinding getBinding(LayoutInflater layoutInflater) {
        return ActivityRemandSelectedGoodsBinding.inflate(layoutInflater);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mToolBinding.toolbarContentTitle.setText("选择物品归还");
        binding.textReturn.setText("归还");
        binding.commonSelectGoods.tvAddGoods.setText("选择物品归还");
        binding.recyclerView.setAdapter(getAdapter());
        super.initData(savedInstanceState);
        initListener();
    }

    /*@Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(SortListBeanEvent sortListBeanEvent) {
        mSortListBeanEvent = sortListBeanEvent;
    }*/

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onDataEvent(RecordRemandBeanEvent event) {
        List<RecordRemandBean> recordRemandBeanList = event.getRecordRemandBeanList();
        if (mSortBean != null) {
            mSortBean.setRecordList(recordRemandBeanList);
            int count = getTotalRecordCount(mSortBean);
            mSortBean.setDefaultLocatStock(count, locationId, locationName);
            mAdapter.setData(mSelectedPosition, mSortBean);
            setButtonState();
        }
    }

    public int getTotalRecordCount(SortBean sortBean) {
        if (sortBean.getRecordList() == null || sortBean.getRecordList().size() == 0) {
            return 0;
        }
        int count = 0;
        for (RecordRemandBean bean : sortBean.getRecordList()) {
            Integer returnNum = bean.getReturnNum();
            if (returnNum != null) {
                count += returnNum;
            }
        }
        return count;
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void setButtonState() {
        textViewState();
    }

    protected void textViewState() {
        List<SortBean> data = mAdapter.getData();
        int total = 0;
        for (SortBean sortBean : data) {
            List<RecordRemandBean> recordList = sortBean.getRecordList();
            if (recordList != null && !recordList.isEmpty()) {
                total += recordList.size();
            }
        }
        binding.textReturn.setEnabled(total > 0);
    }

    protected void initListener() {
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            mSelectedPosition = position;
            SortBean sortBean = mAdapter.getData().get(position);
            if (R.id.tv_loc == view.getId()) {
                goLocActivity(sortBean);
            } else if (R.id.cl_root == view.getId()) {
                mSortBean = sortBean;
                goSelectedOrderActivity(sortBean);
            } else if (R.id.iv_delete == view.getId()) {
                adapter.removeAt(position);
                textViewState();
            }
        });
        binding.commonSelectGoods.llAdd.setOnClickListener(v -> goSelectedGoodsActivity());
    }

    @Override
    protected void submit() {
        List<SortBean> newList = getNewListNotRecordList(mAdapter.getData());
        mRemandReturnBean.setSortList(newList);
        if (mRemandHomePresenter != null) {
            mRemandHomePresenter.directReturn(mRemandReturnBean, 0);
        }
    }

    public List<SortBean> getNewListNotRecordList(List<SortBean> list) {
        List<SortBean> newList = new ArrayList<>();
        if (list == null || list.isEmpty()) {
            return newList;
        }
        for (SortBean sortBean : list) {
            List<RecordRemandBean> recordList = sortBean.getRecordList();
            if (recordList != null && !recordList.isEmpty()) {
                newList.add(sortBean);
            }
        }
        return newList;
    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {
        super.showHttpResponse(httpResponse);
        if (RemandHomePresenter.TAG_REMAND_DIRECT_RETURN.equals(httpResponse.getRequestTag())) {
            EventBus.getDefault().postSticky(new RemandSelectOrderEvent());
            showToast("归还成功");
            finish();
        }
    }

    /**
     * 选择位置
     *
     * @param sortBean
     */
    private void goLocActivity(SortBean sortBean) {
        EventBus.getDefault().postSticky(new SaveLocationEvent(sortBean, sortBean.getTotalReturnNum(), true));
        startActivity(new Intent(getContext(), SaveLocActivity.class));
    }

    /**
     * 选择借用/领用单
     *
     * @param sortBean
     */
    private void goSelectedOrderActivity(SortBean sortBean) {
        EventBus.getDefault().postSticky(new RemandSelectedGoodsEvent(sortBean));
        startActivity(new Intent(getContext(), RemandSelectedOrderActivity.class));
    }

    @Override
    protected void goSelectedGoodsActivity() {
        OperationEvent event = new OperationEvent(getAdapter().getData());
        event.setPasteCode(false);
        EventBus.getDefault().postSticky(event);
        Intent intent = new Intent(getContext(), SelectGoodsActivity.class);
        intent.putExtra("isHiddenAddGoods", true);
        startActivity(intent);
    }

    @Override
    protected BaseQuickAdapter<SortBean, ?> getAdapter() {
        if (mAdapter == null) {
            mAdapter = new RemandSelectedGoodsAdapter(R.layout.item_remand_selected_goods, new ArrayList<>());
            mAdapter.setOnItemChangeListener(new OnItemChangeListener() {
                @Override
                public void onChange(int position) {
                    textViewState();
                }

                @Override
                public void add(int position) {

                }

                @Override
                public void remove(int position) {

                }
            });
        }
        return mAdapter;
    }

    @Override
    protected Button getButton() {
        return binding.textReturn;
    }
}
